package com.sk.weichat.ui.message.single;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.ChatRecordBean;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.User;
import com.sk.weichat.broadcast.MsgBroadcast;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.MainActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.groupchat.SelectContactsActivity;
import com.sk.weichat.ui.groupchat.TabSelectContactsActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.ChatBackgroundActivity;
import com.sk.weichat.ui.message.search.SearchChatHistoryActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DateUtils;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.MsgSaveDaysDialog;
import com.sk.weichat.view.SelectionFrame;
import com.suke.widget.SwitchButton;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by Administrator on 2018/4/18 0018.
 */

public class PersonSettingActivity extends BaseActivity implements View.OnClickListener {

    private ImageView mFriendAvatarIv;
    private TextView mFriendNameTv;
    private SwitchButton mIsReadFireSb;
    private SwitchButton mTopSb;
    private SwitchButton mIsDisturbSb;
    private TextView mMsgSaveDays;

    private String mLoginUserId;
    private String mFriendId;
    private int mReplyStatus;
    private final int request_set_bg = 7823;
    MsgSaveDaysDialog.OnMsgSaveDaysDialogClickListener onMsgSaveDaysDialogClickListener = new MsgSaveDaysDialog.OnMsgSaveDaysDialogClickListener() {

        @Override
        public void itemClick(double chatRecordTimeOut, String chatRecordTimeOutStr) {
            updateChatRecordTimeOut(chatRecordTimeOut, chatRecordTimeOutStr);
        }
    };
    private Friend mFriend;
    private String mFriendName;
    private RefreshBroadcastReceiver receiver = new RefreshBroadcastReceiver();
    private CheckBox mCheckSex;
    private TextView mTvSignature;
    private TextView mTvRemark;
    private TextView mTvDesc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_setting);

        mLoginUserId = coreManager.getSelf().getUserId();
        mFriendId = getIntent().getStringExtra("ChatObjectId");
        mReplyStatus = getIntent().getIntExtra("ReplyStatus", -1);
        mFriend = FriendDao.getInstance().getFriend(mLoginUserId, mFriendId);

        initActionBar();
        initView();
        registerReceiver();

        getOtherUserInfo(mFriendId);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFriend = FriendDao.getInstance().getFriend(mLoginUserId, mFriendId);// Friend也更新下
        if (mFriend == null) {
            Toast.makeText(this, R.string.tip_friend_removed, Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, MainActivity.class));
            finish();
        } else {
            mFriendName = TextUtils.isEmpty(mFriend.getRemarkName()) ? mFriend.getNickName() : mFriend.getRemarkName();
            mFriendNameTv.setText(mFriendName);

            if (!TextUtils.isEmpty(mFriend.getDescribe())) {
                mTvRemark.setText("描述");
                mTvDesc.setVisibility(View.VISIBLE);
                mTvDesc.setText(mFriend.getDescribe());
            } else {
                mTvRemark.setText(R.string.set_remark_and_describe);
                mTvDesc.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(Color.parseColor("#00000000"));
        findViewById(R.id.iv_title_left).setOnClickListener(this);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText(getString(R.string.chat_settings));
    }

    private void initView() {
        mFriendAvatarIv = (ImageView) findViewById(R.id.avatar_img);

        AvatarHelper.getInstance().displayAvatar(mFriendId, mFriendAvatarIv, false);
        mFriendNameTv = (TextView) findViewById(R.id.nick_name_tv);
        mCheckSex = findViewById(R.id.checkbox_center_sex);
        mTvSignature = findViewById(R.id.tv_person_setting_signature);
        mTvRemark = findViewById(R.id.tv_person_setting_remark);
        mTvDesc = findViewById(R.id.tv_person_setting_desc);

        // 阅后即焚 && 置顶 && 消息免打扰
        mIsReadFireSb = (SwitchButton) findViewById(R.id.sb_read_fire);
        int isReadDel = PreferenceUtils.getInt(mContext, Constants.MESSAGE_READ_FIRE + mFriendId + mLoginUserId, 0);
        mIsReadFireSb.setChecked(isReadDel == 1);
        mIsReadFireSb.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                PreferenceUtils.putInt(mContext, Constants.MESSAGE_READ_FIRE + mFriendId + mLoginUserId, isChecked ? 1 : 0);
                if (isChecked) {
//                    TipDialog tipDialog = new TipDialog(PersonSettingActivity.this);
//                    tipDialog.setmConfirmOnClickListener(getString(R.string.tip_status_burn), new TipDialog.ConfirmOnClickListener() {
//                        @Override
//                        public void confirm() {
//                        }
//                    });
//                    tipDialog.show();
                    ToastUtil.showToast(getApplicationContext(), R.string.tip_status_burn);
                }
            }
        });

        mTopSb = (SwitchButton) findViewById(R.id.sb_top_chat);
        mTopSb.setChecked(mFriend.getTopTime() != 0);// TopTime不为0，当前状态为置顶
        mTopSb.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    FriendDao.getInstance().updateTopFriend(mFriendId, mFriend.getTimeSend());
                } else {
                    FriendDao.getInstance().resetTopFriend(mFriendId);
                }
            }
        });

        mIsDisturbSb = (SwitchButton) findViewById(R.id.sb_no_disturb);
        mIsDisturbSb.setChecked(mFriend.getOfflineNoPushMsg() == 1);
        mIsDisturbSb.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                updateDisturbStatus(isChecked);
            }
        });

        mMsgSaveDays = (TextView) findViewById(R.id.msg_save_days_tv);
        mMsgSaveDays.setText(conversion(mFriend.getChatRecordTimeOut()));

        findViewById(R.id.layout_person_setting_info).setOnClickListener(this);
        findViewById(R.id.layout_more_remark).setOnClickListener(this);
        findViewById(R.id.chat_history_search).setOnClickListener(this);
        findViewById(R.id.layout_create_group).setOnClickListener(this);
        findViewById(R.id.msg_save_days_rl).setOnClickListener(this);
        findViewById(R.id.chat_history_empty).setOnClickListener(this);
        findViewById(R.id.set_chat_background).setOnClickListener(this);


        /*悦聊团队账号 特殊处理*/
        if (mFriendId.equals(Friend.ID_SYSTEM_MESSAGE)) {
            findViewById(R.id.img_system_flag).setVisibility(View.VISIBLE);
            mCheckSex.setVisibility(View.GONE);
            mTvSignature.setVisibility(View.GONE);
            findViewById(R.id.layout_more_remark).setVisibility(View.GONE);
            findViewById(R.id.layout_create_group).setVisibility(View.GONE);
            findViewById(R.id.msg_save_days_rl).setVisibility(View.GONE);
            findViewById(R.id.rt_line_none).setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.layout_person_setting_info:
                //个人资料
                Intent intentBasic = new Intent(this, PersonalCenterActivity.class);
                intentBasic.putExtra(AppConstant.EXTRA_USER_ID, mFriendId);
                startActivity(intentBasic);
                break;

            case R.id.layout_more_remark:
                //备注和描述
                Intent intent = new Intent(this, SetRemarkActivity.class);
                intent.putExtra(AppConstant.EXTRA_USER_ID, mFriendId);
                startActivityForResult(intent, SetRemarkActivity.REQUEST_CODE_SET_REMARK);
                break;

            case R.id.chat_history_search:
                Intent intentChat = new Intent(this, SearchChatHistoryActivity.class);
                intentChat.putExtra("isSearchSingle", true);
                intentChat.putExtra(AppConstant.EXTRA_USER_ID, mFriendId);
                startActivity(intentChat);
                break;
            case R.id.layout_create_group:
                //发起群聊
                Intent intentAdd = new Intent(this, TabSelectContactsActivity.class);
                intentAdd.putExtra("QuicklyCreateGroup", true);
                intentAdd.putExtra("ChatObjectId", mFriendId);
                intentAdd.putExtra("ChatObjectName", mFriendName);
                intentAdd.putExtra("ReplyStatus", mReplyStatus);
                startActivity(intentAdd);
                break;
            case R.id.msg_save_days_rl:
                if (coreManager.readConfigBean() == null) {
                    return;
                }
                MsgSaveDaysDialog msgSaveDaysDialog = new MsgSaveDaysDialog(this, coreManager.readConfigBean().getChatRecordTimeOutList(), onMsgSaveDaysDialogClickListener);
                msgSaveDaysDialog.show();
                break;
            case R.id.chat_history_empty:
                emptyServerMessage();

                // 清空聊天记录
                SelectionFrame selectionFrame = new SelectionFrame(mContext);
                selectionFrame.setSomething(null, getString(R.string.tip_confirm_clean_history), new SelectionFrame.OnSelectionFrameClickListener() {
                    @Override
                    public void cancelClick() {

                    }

                    @Override
                    public void confirmClick() {
                        FriendDao.getInstance().resetFriendMessage(mLoginUserId, mFriendId);
                        ChatMessageDao.getInstance().deleteMessageTable(mLoginUserId, mFriendId);
                        sendBroadcast(new Intent(Constants.CHAT_HISTORY_EMPTY));// 清空聊天界面
                        MsgBroadcast.broadcastMsgUiUpdate(mContext);
                        Toast.makeText(PersonSettingActivity.this, getString(R.string.delete_success), Toast.LENGTH_SHORT).show();
                    }
                });
                selectionFrame.show();
                break;

            case R.id.set_chat_background:
                //设置聊天背景图

                ChatBackgroundActivity.startChatBackgroundActivityForResult(PersonSettingActivity.this, mLoginUserId + mFriendId, request_set_bg);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        if (resultCode == Activity.RESULT_OK || request_set_bg == requestCode) {
            finish();
        }
        switch (requestCode) {
            case SetRemarkActivity.REQUEST_CODE_SET_REMARK:
                getOtherUserInfo(mFriendId);
                break;
        }
    }

    /**
     * 获取他人的个人信息
     *
     * @param mUserId 他人的userId
     */
    public void getOtherUserInfo(String mUserId) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("userId", mUserId);

        HttpUtils.get().url(coreManager.getConfig().USER_GET_URL)
                .params(params)
                .build()
                .execute(new BaseCallback<User>(User.class) {

                    @Override
                    public void onResponse(ObjectResult<User> result) {
                        if (Result.checkSuccess(mContext, result)) {
                            User user = result.getData();

                            if (user.getFriends() != null) {
                                if (!TextUtils.isEmpty(user.getFriends().getRemarkName())) {
                                    mFriendNameTv.setText(user.getFriends().getRemarkName());
                                }
                                if (!TextUtils.isEmpty(user.getFriends().getDescribe())) {
                                    mTvRemark.setText("描述");
                                    mTvDesc.setVisibility(View.VISIBLE);
                                    mTvDesc.setText(user.getFriends().getDescribe());
                                } else {
                                    mTvRemark.setText(R.string.set_remark_and_describe);
                                    mTvDesc.setVisibility(View.GONE);
                                }
                            }

                            if (user.getSex() == 0) {//女
                                mCheckSex.setChecked(false);
                            } else {
                                mCheckSex.setChecked(true);
                            }
                            mCheckSex.setText(DateUtils.getAge(new Date(user.getBirthday() * 1000)) + "");

                            if (!TextUtils.isEmpty(user.getDescription())) {
                                mTvSignature.setText(user.getDescription());
                            } else {
                                mTvSignature.setText(getString(R.string.signature_describe_empty));
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        ToastUtil.showNetError(mContext);
                    }
                });
    }

    // 更新消息免打扰状态
    private void updateDisturbStatus(final boolean isChecked) {
        final String offlineNoPushMsg = isChecked ? "1" : "0";
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("userId", mLoginUserId);
        params.put("toUserId", mFriendId);
        params.put("offlineNoPushMsg", offlineNoPushMsg);
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().FRIENDS_NOPULL_MSG)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            FriendDao.getInstance().updateOfflineNoPushMsgStatus(mFriendId, isChecked ? 1 : 0);
                        } else {
                            Toast.makeText(PersonSettingActivity.this, R.string.tip_edit_failed, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(PersonSettingActivity.this);
                    }
                });
    }

    // 更新消息保存天数
    private void updateChatRecordTimeOut(final double outTime, String chatRecordTimeOutStr) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("toUserId", mFriendId);
        params.put("chatRecordTimeOut", String.valueOf(outTime));

        HttpUtils.get().url(coreManager.getConfig().FRIENDS_UPDATE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            Toast.makeText(PersonSettingActivity.this, getString(R.string.update_success), Toast.LENGTH_SHORT).show();
                            mMsgSaveDays.setText(conversion(outTime));
                            FriendDao.getInstance().updateChatRecordTimeOut(mFriendId, outTime);
                            sendBroadcast(new Intent(com.sk.weichat.broadcast.OtherBroadcast.NAME_CHANGE));// 刷新聊天界面
                        } else {
                            Toast.makeText(PersonSettingActivity.this, result.getResultMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    // 服务器上与该人的聊天记录也需要删除
    private void emptyServerMessage() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("type", String.valueOf(0));// 0 清空单人 1 清空所有
        params.put("toUserId", mFriendId);

        HttpUtils.get().url(coreManager.getConfig().EMPTY_SERVER_MESSAGE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {

                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    private String conversion(double outTime) {
        if (coreManager.readConfigBean() == null || coreManager.readConfigBean().getChatRecordTimeOutList() == null) {
            return "";
        }
        List<ChatRecordBean> chatRecordTimeOutList = coreManager.readConfigBean().getChatRecordTimeOutList();
        String outTimeStr = "";
        for (ChatRecordBean chatRecordBean : chatRecordTimeOutList) {
            if (outTime == chatRecordBean.getChatRecordTimeOut()) {
                outTimeStr = chatRecordBean.getChatRecordTimeOutStr();
                break;
            }
        }
        if (TextUtils.isEmpty(outTimeStr)) {
            outTimeStr = chatRecordTimeOutList.get(0).getChatRecordTimeOutStr();
            FriendDao.getInstance().updateChatRecordTimeOut(mFriendId, chatRecordTimeOutList.get(0).getChatRecordTimeOut());
        }

        return outTimeStr;
    }

    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(com.sk.weichat.broadcast.OtherBroadcast.QC_FINISH);
        registerReceiver(receiver, intentFilter);
    }

    public class RefreshBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(com.sk.weichat.broadcast.OtherBroadcast.QC_FINISH)) {
                // 快速创建群组 || 更换聊天背景 成功，接收到该广播结束当前界面
                finish();
            }
        }
    }
}
